// Copyright 2008-2009 Louis DeJardin - http://whereslou.com
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// 
using System;
using Spark.Compiler;
using Spark.Compiler.ChunkVisitors;
using Spark.Parser.Code;

namespace NRails.Spark.ChunkVisitors
{
    public class BaseClassVisitor : ChunkVisitor
    {
        public BaseClass : Snippets { get; set; }
        public TModel : Snippets { get; set; }

        mutable _encounteredBaseClass : bool;
        mutable _encounteredTModel : bool;

        public BaseClassTypeName : Snippets
        {
            get
            {
                def baseClass = if (Snippets.IsNullOrEmpty(BaseClass))
                    "Spark.SparkViewBase" : Snippets
                else
                    BaseClass;

                if (Snippets.IsNullOrEmpty(TModel))
                    baseClass;
                else
                {
                    def s1 = Snippet();
                    s1.Value = "[";
                    baseClass.Add(s1);
                    
                    baseClass.AddRange(TModel);
                    
                    def s2 = Snippet();
                    s2.Value = "]";
                    baseClass.Add(s2);                    

                    def s = Snippets();
                    s.AddRange(baseClass);
                    s
                }                   
            }
        }

        protected override Visit(chunk : ViewDataModelChunk) : void 
        {
            when (_encounteredTModel && !string.Equals(TModel, chunk.TModel, StringComparison.Ordinal))
            {
                throw CompilerException(string.Format("Only one viewdata model can be declared. {0} != {1}", TModel,
                                                          chunk.TModel));
            }
            TModel = chunk.TModel;
            _encounteredTModel = true;
        }

        protected override Visit(chunk : PageBaseTypeChunk) : void
        {
            when (_encounteredBaseClass && !string.Equals(BaseClass, chunk.BaseClass, StringComparison.Ordinal))
            {
                throw CompilerException(string.Format("Only one pageBaseType can be declared. {0} != {1}", BaseClass,
                                                          chunk.BaseClass));
            }
            BaseClass = chunk.BaseClass;
            _encounteredBaseClass = true;
        }
    }
}
